package com.server.common.beanvalidator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by 金贤哲 on 2017/5/22 0022.
 */
public class MustPhoneNumValidator  implements ConstraintValidator<MustPhoneNum,String> {
    private int len;
    /**
     * 初始参数,获取注解中length的值
     */
    @Override
    public void initialize(MustPhoneNum arg0) {
        this.len = arg0.length();
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
        if(isChinaPhoneLegal(str)){
           return true;
        }else{
          //  constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值
            //重新添加错误提示语句
            //constraintValidatorContext
              //      .buildConstraintViolationWithTemplate("字符串不能为空").addConstraintViolation();
        }
        return false;
    }
    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public  boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9])|(17[0-8]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
